package com.yang.ddz.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.concurrent.ExecutorService;

public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
    private ExecutorService httpExecutor;


    public ChildChannelHandler(ExecutorService httpExecutor) {
        this.httpExecutor = httpExecutor;
    }

    @Override
    //websocket与http使用同一netty服务器是为了端口统一
    protected void initChannel(SocketChannel ch) throws Exception {
        //继承了ChannelHandlerAppender，并且创建了一个HttpRequestDecode和一个HttpResponseEncoder
        ch.pipeline().addLast(new HttpServerCodec());

        // 目的是将多个消息转换为单一的request或者response对象,参数为聚合后http请求的大小线程
        ch.pipeline().addLast(new HttpObjectAggregator(64 * 1024));

        //目的是支持异步大文件传输，websocket通讯需要
        ch.pipeline().addLast(new ChunkedWriteHandler());

        //http业务逻辑
        ch.pipeline().addLast(new HttpServerRequestHandler(httpExecutor, "/http"));

        //支持websocket通讯
        //插入位置，顺序非常重要，必须插在http编解码器的后面，必须插在当前处理器的前面
        //处理ping-pong 二帧。
        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/srws"));

        //websocket业务逻辑
        ch.pipeline().addLast(new WebSocketHandler());

    }

}
